//
//  Textfield+Extension.swift
//  IMIHome
//
//  Created by Roffa Zhou on 2021/9/7.
//  Copyright © 2021 上海创米科技有限公司. All rights reserved.
//

import Foundation

public extension UITextField {
    /**简单通过响应链解耦实现textfield键盘出现后，位置调整*/
    func listen(){
        NotificationCenter.default.addObserver(self, selector: #selector(ls_begin), name: UITextField.textDidBeginEditingNotification, object: nil)
        NotificationCenter.default.addObserver(self, selector: #selector(ls_end), name: UITextField.textDidEndEditingNotification, object: nil)        
    }
    
    /// 找到当前textfield所在的viewcontroller.view的一级子视图
    /// - Returns: 返回找到的视图
    private func frameView()->UIView{
        var view = self.superview
        while view != nil, view?.superview != self.viewController?.view {
            view = view!.superview
        }
        return view!
    }
    
    /// 键盘将要展开
    @objc private func ls_begin(){
        if self.viewController?.view.transform == .identity {
            if self.viewController!.view.viewWithTag(2021090700) == nil {  //增加一层遮罩
                let coverView = UIView()
                coverView.tag = 2021090700
                self.viewController!.view.addSubview(coverView)
                coverView.isUserInteractionEnabled = true
                coverView.snp.makeConstraints { make in
                    make.left.top.right.equalTo(0)
                    make.bottom.equalTo(self.snp.top)
                }
                coverView.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(closeKeyboard)))
            }
            UIView.animate(withDuration: 0.3) {
                self.frameView().transform = CGAffineTransform(translationX: 0, y: self.viewController!.view.height - self.frameView().maxY - 320)
            }
        }
    }
    @objc private func ls_end(){
        UIView.animate(withDuration: 0.3) {
            self.frameView().transform = CGAffineTransform.identity
        }
    }
    @objc private func closeKeyboard(){
        resignFirstResponder()
        let view = self.viewController!.view.viewWithTag(2021090700)
        if view != nil {
            view!.removeFromSuperview()
        }
    }
}
